<template>
  <div class="page-container">
    <page-form :model="form" ref="formRef" :rules="rules" layout="vertical">
      <card class="car-model-999" title="车辆基本信息" toggle>
        <page-form-row>
          <page-form-item style="position: relative" field="modelId" label="车型" required size="2/3">
            <!-- 车型选择 -->
            <remote-select
              v-model="form.modelId"
              placeholder="请选择"
              :disabled="status == 'edit'"
              :params="{ id: defaultModelId }"
              type="car_model_tenantList"
              @change="carModelChangeFn"
            />
            <div class="operate-list" :style="{ right: status == 'new' ? '-236px' : '-134px' }">
              <a-button class="operate-btn" v-if="status == 'new'" type="primary" @click="addCarModelFn">添加车型</a-button>
              <div class="inline-block">
                <car-model-popup
                  :disabled="!form.modelId"
                  ref="carModelPopupRef"
                  :modelId="form.tenantModelId"
                  popupContainer=".car-model-999"
                />
              </div>
            </div>
          </page-form-item>
          <div class="w-full"></div>
          <!-- 门店 && 车场 门店选择完需要自动带出车场 -->
          <page-form-item field="siteId" label="归属门店" required>
            <remote-select
              v-model="form.siteId"
              placeholder="请选择"
              :params="{ oldId: form.oldId, siteStatusList: [10] }"
              type="site_listBystaff"
              @change="changeSiteFn"
            />
          </page-form-item>
          <page-form-item field="garage" label="归属车场" wrap>
            <a-input v-model="form.libraryName" placeholder="-" disabled />
          </page-form-item>
          <!-- 门店 && 车场 -->
          <car-source />
          <page-form-item field="carColor" label="车辆颜色" wrap>
            <i-input placeholder="请输入车辆颜色" v-model="form.carColor" :max-length="10" />
          </page-form-item>
          <page-form-item label="GPS设备" size="1" style="margin-bottom: 0" field="vehicleIdList">
            <div class="page-form-block">
              <page-form-row v-for="(item, index) in form.vehicleIdList" :key="index">
                <page-form-item style="position: relative" size="2/3" :field="`vehicleIdList.${index}`">
                  <remote-select
                    :disabled="item.disabled"
                    v-model="item.id"
                    placeholder="请选择"
                    type="car_vehicle_list"
                    :params="{
                      idList: item.id ? [+item.id] : undefined,
                      autoincrement: upper,
                      statusList: [0, 1], // 已使用、未使用
                    }"
                    @change="changeVehicleIdFn"
                  >
                    <template #option="{ option }">
                      {{ option.vehicleSelectStr }}
                      <tag :type="option.status == 1 ? 'warn' : 'primary'" style="margin-left: 6px">{{ option.statusStr }}</tag>
                    </template>
                  </remote-select>
                  <operate-list
                    :style="{ top: '0px' }"
                    :index="index"
                    :item="item"
                    :length="form.vehicleIdList.length"
                    @add="newVehicleFn"
                    @delete="delVehicleFn"
                    @unbind="unbindFn"
                  />
                </page-form-item>
              </page-form-row>
            </div>
          </page-form-item>
        </page-form-row>
      </card>
      <card title="行驶证信息" toggle>
        <a-alert>
          请上传行驶证正/副页。支持的格式：JPG、JPEG、PNG、WEBP。请保证图片内容清晰、无反光、无折痕、背景无杂物；下方需要填写的信息要求与行驶本一致。
          <!-- <a-button type="text" size="mini">查看示例</a-button> -->
        </a-alert>
        <page-form-row class="upload-wrapper">
          <page-form-item field="driveImgFrontFileId" label="上传行驶证正页">
            <upload-ocr ref="uploadOcrRef" v-model="form.driveImgFrontFileId" ocrType="font" @ocrClick="fontChange" />
          </page-form-item>
          <page-form-item field="driveImgBackFileId" label="上传行驶证副页">
            <upload-ocr ref="uploadOcrRef" v-model="form.driveImgBackFileId" ocrType="back" @ocrClick="backChange" />
          </page-form-item>
          <page-form-item field="carHeadFileId" label="车头照">
            <upload-ocr ref="uploadOcrRef" v-model="form.carHeadFileId" />
          </page-form-item>
          <page-form-item field="licenseNo" label="车牌号" required>
            <i-input v-model="form.licenseNo" @blur="editCarInfoFn" :max-length="10" />
          </page-form-item>
          <page-form-item field="vin" label="车架号-车辆识别代码" required>
            <i-input v-model="form.vin" :max-length="30" @change="editCarVinFn" />
          </page-form-item>
          <page-form-item field="licenseNoColor" label="车牌颜色">
            <template #extra>
              <div class="text-red-500">注意：请选择车牌颜色！不是车身颜色</div>
            </template>
            <a-select v-model="form.licenseNoColor" placeholder="请选择" @change="editCarInfoFn">
              <a-option v-for="item in carSyncHrhcDict.licenseNoColorList" :key="item.value" :value="item.value" :label="item.label" />
            </a-select>
          </page-form-item>
          <page-form-item field="engineNum" label="发动机号">
            <i-input v-model="form.engineNum" :max-length="30" />
          </page-form-item>
          <page-form-item field="brandModel" label="品牌型号">
            <i-input v-model="form.brandModel" :max-length="36" />
          </page-form-item>
          <page-form-item field="driveNatureOwner" label="行驶证所属人姓名">
            <i-input v-model="form.driveNatureOwner" :max-length="50" />
          </page-form-item>
          <page-form-item field="drivingAddress" label="住址">
            <i-input v-model="form.drivingAddress" :max-length="99" />
          </page-form-item>
          <page-form-item field="registerDate" label="注册日期">
            <i-date-picker class="w-full" v-model="form.registerDate" />
          </page-form-item>
          <page-form-item field="issuanceDate" label="发证日期">
            <i-date-picker class="w-full" v-model="form.issuanceDate" />
          </page-form-item>
          <page-form-item field="driverUseNature" label="使用性质">
            <i-input v-model="form.driverUseNature" :max-length="64" />
          </page-form-item>
          <page-form-item field="grossMass" label="总质量（单位：千克）">
            <i-input-number v-model="form.grossMass" :precision="0" unit="千克" />
          </page-form-item>
          <page-form-item field="unladenMass" label="整备质量（单位：千克）">
            <i-input-number v-model="form.unladenMass" :precision="0" unit="千克" />
          </page-form-item>
          <page-form-item label="外廓尺寸（单位：毫米）">
            <i-input-number v-model="form.length" :precision="0" placeholder="车长" unit="" />
            <span class="mx-1">x</span>
            <i-input-number v-model="form.width" :precision="0" placeholder="车宽" unit="" />
            <span class="mx-1">x</span>
            <i-input-number v-model="form.height" :precision="0" placeholder="车高" unit="" />
          </page-form-item>
          <page-form-item field="ac" label="核定载人数">
            <i-input-number v-model="form.ac" :precision="0" unit="人" />
          </page-form-item>
          <!-- 2025-1-20补充 -->
          <page-form-item field="driverCarType" label="车辆类型">
            <a-auto-complete
              allow-clear
              v-model="form.driverCarType"
              :data="
                (carSyncHrhcDict.driverCarTypeList || []).map((item) => ({
                  ...item,
                  value: item.label,
                }))
              "
              placeholder="请输入"
              :max-length="99"
            />
          </page-form-item>
        </page-form-row>
      </card>
      <!-- 编辑的时候不显示 年检、保险等信息 -->
      <template v-if="status == 'new'">
        <card title="年检证" toggle :showDivider="status == 'new'">
          <a-alert class="mb-4 car-manage-alert">
            1、年检证建议上传12123电子年检证。支持的格式：JPG、JPEG、PNG、WEBP。<a-link @click="exampleVisible = true">示例</a-link
            >，<a-link @click="openHelp">电子年检证获取路径</a-link>；
            <br />
            2、此处上传的年检证仅做暂时保存，后续会根据最新上传的覆盖掉。如果需要长久留存，可通过【新增年检】功能上传年检证；
          </a-alert>
          <a-image-preview :src="exampleImg" v-model:visible="exampleVisible" />
          <page-form-row>
            <page-form-item field="inspectionFileId" label="上传年检证">
              <upload-ocr v-model="form.inspectionFileId" ocrType="inspection" @ocrClick="inspectionFileIdOCRSuccess" />
            </page-form-item>
            <page-form-item label="年检有效期至" field="planTime">
              <i-date-picker class="w-full" v-model="form.planTime" value-format="YYYY-MM-DD" :disabled="form.existInspection" />
            </page-form-item>
          </page-form-row>
        </card>
        <!-- 交强保险单 -->
        <card title="交强保险单" toggle :toggleDefault="false">
          <div class="empty-custom-fee flex" v-if="form.compulsory.length == 0">
            <div class="empty-custom-fee-content">
              <a-empty description="暂无交强保险单" />
              <a-button type="primary" @click="addInsureFn('compulsory')">
                <template #icon>
                  <icon-plus />
                </template>
                新增交强保险单
              </a-button>
            </div>
          </div>
          <compulsory operateType="addInsure" v-else />
        </card>
        <!-- 商业保险单 -->
        <card title="商业保险单" toggle :toggleDefault="false">
          <div class="empty-custom-fee flex" v-if="form.business.length == 0">
            <div class="empty-custom-fee-content">
              <a-empty description="暂无商业保险单" />
              <a-button type="primary" @click="addInsureFn('business')">
                <template #icon>
                  <icon-plus />
                </template>
                新增商业保险单
              </a-button>
            </div>
          </div>
          <business operateType="addInsure" v-else />
        </card>
      </template>
      <!-- 运维信息部分 -->
      <card title="运维信息" v-if="status == 'edit'" toggle>
        <a-alert class="mb-4 car-manage-alert">
          此处上传的年检证、保单仅做暂时保存，后续会根据最新上传的覆盖掉。如果需要长久留存，可通过【新增年检】【新增保单】功能上传凭证。
        </a-alert>
        <page-form-row>
          <page-form-item field="inspectionFileId" label="年检证">
            <upload-ocr
              ref="inspectionUploadOcrRef"
              v-model="form.inspectionFileId"
              ocrType="inspection"
              @ocrClick="inspectionFileIdOCRSuccess"
            />
          </page-form-item>
          <page-form-item field="planTime" label="年检有效期至">
            <i-date-picker class="w-full" v-model="form.planTime" />
            <a-button type="primary" @click="inspectAddModalFn" class="ml-2">
              <icon-plus />
              <span>新增年检</span>
            </a-button>
          </page-form-item>
          <page-form-item />
          <page-form-item field="businessFileId" label="商业保险单">
            <upload-attach ref="businessUploadOcrRef" v-model="form.businessFileId" :accept="['PDF', 'JPG', 'PNG']" />
          </page-form-item>
          <page-form-item field="businessEndDate" label="商业险到期日">
            <i-date-picker class="w-full" v-model="form.businessEndDate" />
            <a-button class="ml-2" type="primary" @click="addInsureModalFn(1)">
              <icon-plus />
              新增保单
            </a-button>
          </page-form-item>
          <page-form-item />
          <page-form-item field="compulsoryFileId" label="交强险保单">
            <upload-attach ref="compulsoryUploadOcrRef" v-model="form.compulsoryFileId" :accept="['PDF', 'JPG', 'PNG']" />
          </page-form-item>
          <page-form-item field="compulsoryEndDate" label="交强险到期日">
            <i-date-picker class="w-full" v-model="form.compulsoryEndDate" />
            <a-button class="ml-2" type="primary" @click="addInsureModalFn(0)">
              <icon-plus />
              新增保单
            </a-button>
          </page-form-item>
          <page-form-item />
          <page-form-item field="totalMileage" label="车辆当前行驶里程">
            <i-input-number v-model="form.totalMileage" :precision="0" unit="公里" />
          </page-form-item>
          <page-form-item field="estimatedKilometre" label="下次保养里程">
            <i-input-number v-model="form.estimatedKilometre" :precision="0" unit="公里" />
            <a-button class="ml-2" type="primary" @click="maintenanceAddModalFn">
              <icon-plus />
              新增保养
            </a-button>
          </page-form-item>
          <page-form-item field="estimatedTime" label="下次保养日期">
            <i-date-picker class="w-full" v-model="form.estimatedTime" />
          </page-form-item>
        </page-form-row>
      </card>
      <!-- tbox和etc设备信息只在编辑时展示，并且不能修改 -->
      <template v-if="status == 'edit'">
        <!-- 判断商户是否开启TBOX -->
        <card title="车载BOX设备信息" toggle v-if="userStore.enterpriseDetail.tboxEnabled == 1">
          <page-form-row class="upload-wrapper">
            <page-form-item label="设备状态">
              <i-input v-model="form.tboxEquipmentStatusName" placeholder="无设备" disabled />
            </page-form-item>
            <page-form-item label="车载BOX车辆当前公里数">
              <i-input-number v-model="form.tboxCurrentMileage" placeholder="0.00" disabled unit="公里" />
            </page-form-item>
            <page-form-item label="车载BOX车辆当前油（电）量">
              <i-input-number v-model="form.tboxCurrentOil" placeholder="0" disabled :min="1" :max="99999" unit="" />
            </page-form-item>
            <page-form-item label="设备供应商">
              <i-input v-model="form.tboxVehicleFirm" disabled />
            </page-form-item>
          </page-form-row>
        </card>
        <!-- 判断商户是否开启ETC -->
        <card
          title="ETC设备信息"
          toggle
          v-if="userStore.enterpriseDetail.hrhcEtcEnabled == 1 || userStore.enterpriseDetail.quantumEtcEnabled == 1"
        >
          <page-form-row class="upload-wrapper">
            <page-form-item label="设备是否激活">
              <i-input v-model="form.etcEquipmentActivationName" placeholder="无设备" disabled />
            </page-form-item>
            <page-form-item label="ETC设备号">
              <i-input v-model="form.etcEquipmentNo" placeholder="无设备" disabled />
            </page-form-item>
            <page-form-item label="ETC卡号">
              <i-input v-model="form.etcCardNo" placeholder="无设备" disabled />
            </page-form-item>
            <page-form-item label="设备是否在线">
              <i-input v-model="form.etcEquipmentOnLineName" placeholder="无设备" disabled />
            </page-form-item>
            <page-form-item label="硬件连接状态">
              <i-input v-model="form.etcHardwareStatusName" placeholder="无设备" disabled />
            </page-form-item>
            <page-form-item label="设备工作状态">
              <i-input v-model="form.etcWorkStatusName" placeholder="无设备" disabled />
            </page-form-item>
          </page-form-row>
        </card>
      </template>

      <!-- 添加车型弹窗 -->
      <car-model-new-modal ref="newCarModelRef" @success="newCarModelSuccessFn" />
    </page-form>
  </div>
  <page-form-footer :ok-loading="okLoading" @ok="submitFn" />
  <!-- 保险新增弹窗 -->
  <insure-add-modal ref="insureAddModalRef" @ok="insureAddOk" />
  <!-- 新增保养 -->
  <maintenanceAddModal ref="maintenanceAddModalRef" @ok="maintenanceAddOk" />
  <!-- 新增年检 -->
  <inspectAddModal ref="inspectAddModalRef" @ok="inspectAddOk" />
</template>

<script setup name="CarManageForm">
  import exampleImg from '@/assets/help/example_AS.png'
  import operateList from './components/operte-list.vue'
  import carModelNewModal from './components/car-model-new-modal.vue'
  import carSource from './components/car-source.vue'
  import carModelPopup from '../components/car-model-popup.vue'
  import compulsory from '@/views/assets/operation/car-insure/components/insurance-policy/compulsory.vue'
  import business from '@/views/assets/operation/car-insure/components/insurance-policy/business.vue'
  import insureAddModal from '@/views/assets/operation/car-insure/components/insure-add-modal.vue'
  import maintenanceAddModal from '@/views/assets/operation/car-maintenance/car-maintenance-form-modal.vue'
  import InspectAddModal from '@/views/assets/operation/car-inspect/car-inspect-form-modal.vue'
  import { ref, provide, computed, onMounted } from 'vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { useRoute } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import { getCarModelDetail } from '@/api/asset/carModel.js'
  import { modifyCar, checkLicenseNo, checkReturnCar, getCarDetail } from '@/api/asset/car.js'
  import useNavigate from '@/hooks/useNavigate'
  import dayjs from 'dayjs'
  import useUserStore from '@/store/modules/user'
  import { isValid } from '@/utils'

  const { navigateBack, navigateTo } = useNavigate()

  // 根据商户是否开启etc和tbox来增加搜索条件和对应列
  const userStore = useUserStore()
  userStore.setEpDetail()

  // 运维信息新增弹窗部分
  const insureAddModalRef = ref()
  const addInsureModalFn = (val) => {
    // 0交强险 1商业险
    insureAddModalRef.value.open(carInfo.value, val)
  }
  // 新增保养
  const maintenanceAddModalRef = ref()
  const maintenanceAddModalFn = () => {
    maintenanceAddModalRef.value.open({ carId: carInfo.value.carId, page: 'carEdit' })
  }
  // 新增年检
  const exampleVisible = ref(false)
  const inspectAddModalRef = ref()
  const inspectAddModalFn = () => {
    inspectAddModalRef.value.open({ carId: carInfo.value.carId, page: 'carEdit' })
  }
  // 查看帮助
  const openHelp = () => {
    window.open('https://image.qichengcx.com/svms/ccms/guide.pdf?#', '_blank')
  }
  // 年检ocr成功回调
  const inspectionFileIdOCRSuccess = (res) => {
    if (res?.date) {
      Message.success('读取成功')
      form.value.planTime = res.date
    }
  }

  const route = useRoute()
  const routePrams = route.params
  const status = ref('new')
  const defaultForm = {
    source: 1,
    contractCarPurchaseEditVo: {
      useInstallment: 0, // 合同是否分期
      lnstalmentNum: 12,
      initialAmount: '',
      balanceAmount: '',
    },
    // 车机设备列表
    vehicleIdList: [{}],
    // 交强险列表 insureKind 固定 0
    compulsory: [],
    // 商业险列表 insureKind 固定 1
    business: [],
  }
  let form = ref({
    ...defaultForm,
  })
  let originDetail = ref({})
  provide('originDetail', originDetail)

  // 新增保险单
  const addInsureFn = (type) => {
    if (type == 'compulsory') {
      form.value.compulsory.push({
        insureKind: 0,
        siteId: form.value.siteId || '',
      })
    }
    if (type == 'business') {
      form.value.business.push({
        insureKind: 1,
        carInsureDetail: [{}],
        siteId: form.value.siteId || '',
      })
    }
  }
  const defaultModelId = ref()
  // 获取车辆详情
  const carInfo = ref({})
  function getCarDetailFn() {
    console.log('🐳 ~ getCarDetailFn ~ form:', form)
    if (routePrams.id) {
      status.value = 'edit'
      getCarDetail({ id: routePrams.id }).then((res) => {
        originDetail.value = JSON.parse(JSON.stringify(res.result))
        const result = res.result
        // 合并信息
        Object.assign(form.value, result)
        // 用来编辑回显
        form.value.oldId = form.value.siteId
        // 处理无法直接合并内容
        // 1 车型选中
        form.value.tenantModelId = form.value.tenantModelId
        // 2 处理车机
        let vehicleList = form.value.vehicleList
        if (vehicleList) {
          form.value.vehicleIdList = vehicleList.map((item) => {
            return { id: item.id, disabled: true }
          })
        } else {
          form.value.vehicleIdList = [{}]
        }
        // 3 处理车辆合同中 payMethod 字段
        let contractInfo = form.value.contractCarPurchaseEditVo
        if (contractInfo) {
          let initialAmount = contractInfo.initialAmount // 首款金额
          let balanceAmount = contractInfo.balanceAmount // 尾款金额
          let initialAmountRate = contractInfo.initialAmountRate // 首款比例
          let balanceAmountRate = contractInfo.balanceAmountRate // 尾款比例
        } else {
          form.value.contractCarPurchaseEditVo = {
            useInstallment: 0, // 合同是否分期
          }
        }
        carInfo.value = {
          carId: routePrams.id,
          licenseNo: result.licenseNo,
          siteId: result.siteId,
          siteName: result.siteName,
        }
        defaultModelId.value = form.value.modelId
      })
    }
  }
  const compulsoryUploadOcrRef = ref()
  const businessUploadOcrRef = ref()
  const insureAddOk = (insureData) => {
    console.log('🐳 ~ insureAddOk ~ insureData:', insureData)
    if (insureData.insureAddList.length) {
      let { endDate, insureKind, policyImgFileId } = insureData.insureAddList[0]
      // 交强险
      if (insureKind == 0) {
        // 如果页面上已存在交强险到期日，则校验保单的到期日是否早于车辆上的交强险到期日，如果早则跳过
        if (form.value.compulsoryEndDate && dayjs(endDate).isBefore(form.value.compulsoryEndDate)) {
          return
        }
        form.value.compulsoryEndDate = endDate
        compulsoryUploadOcrRef.value.update(policyImgFileId)
      }
      // 商业险
      if (insureKind == 1) {
        // 如果页面上已存在商业险到期日，则校验保单的到期日是否早于车辆上的商业险到期日，如果早则跳过
        if (form.value.businessEndDate && dayjs(endDate).isBefore(form.value.businessEndDate)) {
          return
        }
        form.value.businessEndDate = endDate
        businessUploadOcrRef.value.update(policyImgFileId)
      }
    }
  }

  /**
   * 新增保养成功
   * 备注：
   * 后端逻辑：如果新增的下次保养日期比车辆当前的下次保养日期大，则会进行车辆当前行驶里程的更新、下次保养里程的更新等等，以下次保养日期为准
   * 前端回填逻辑：分别比对 车辆当前行驶里程、下次保养里程、下次保养日期，较大（新）则回填
   * 和测试（月超）确认，此处先保持这样
   */
  const maintenanceAddOk = (data) => {
    // 本次保养里程单独比较，如果大于车辆上本次保养里程，则更新到车辆编辑页面，否则不更新
    if (isValid(data.entranceKilometre)) {
      // 如果新增弹窗有值且页面上有值，则比较大小，如果弹窗内小，则不做处理
      if (isValid(form.value.totalMileage) && data.entranceKilometre < form.value.totalMileage) {
        return
      }
      form.value.totalMileage = data.entranceKilometre
    }
    // 1 比较下次保养里程是否比页面上的大，下次保养里程必填
    let isKilometreBiggerThanFormValue = true
    // 如果页面有值
    if (isValid(form.value.estimatedKilometre)) {
      // 并且新增的值比页面上的小
      if (data.estimatedKilometre < form.value.estimatedKilometre) {
        isKilometreBiggerThanFormValue = false
      }
    }
    // 比页面大，直接更新下次保养里程和下次保养日期
    if (isKilometreBiggerThanFormValue) {
      form.value.estimatedKilometre = data.estimatedKilometre
      form.value.estimatedTime = data.estimatedTime
    } else {
      // 2 比页面小，则比对下次保养日期
      if (isValid(data.estimatedTime)) {
        // 如果新增弹窗有值且页面上有值，则比较大小，如果弹窗内小，则不做处理
        if (isValid(form.value.estimatedTime) && dayjs(data.estimatedTime).isBefore(form.value.estimatedTime)) {
          return
        }
        form.value.estimatedTime = data.estimatedTime
      }
    }
  }

  // 新增年检成功
  const inspectionUploadOcrRef = ref()
  const inspectAddOk = (data) => {
    if (data.planTime) {
      if (form.value.planTime && dayjs(data.planTime).isBefore(form.value.planTime)) {
        return
      }
      form.value.planTime = data.planTime
      inspectionUploadOcrRef.value.update(data.inspectionFileId)
    }
  }

  getCarDetailFn()

  // 驾驶证正页
  const fontChange = (e) => {
    if (e) {
      let forntArr = [
        'plateNum',
        'owner',
        'model',
        'vin',
        'issueDate',
        'engineNum',
        'registerDate',
        'useCharacter',
        'vehicleType',
        'address',
      ]
      form.value.licenseNo = form.value.licenseNo || e.plateNum
      form.value.vin = form.value.vin || e.vin
      form.value.engineNum = form.value.engineNum || e.engineNum
      form.value.driverUseNature = form.value.driverUseNature || e.useCharacter
      form.value.brandModel = form.value.brandModel || e.model
      form.value.driveNatureOwner = form.value.driveNatureOwner || e.owner
      form.value.driverCarType = form.value.driverCarType || e.vehicleType
      form.value.drivingAddress = form.value.drivingAddress || e.address
      if (e.registerDate) {
        form.value.registerDate = form.value.registerDate || dayjs(e.registerDate.toString()).format('YYYY-MM-DD')
      }
      if (e.issueDate) {
        form.value.issuanceDate = form.value.issuanceDate || dayjs(e.issueDate.toString()).format('YYYY-MM-DD')
      }
      forntArr.some((item) => [undefined, null, ''].includes(e[item]))
        ? Message.warning(`未全部识别，行驶证正面图片可能不够清晰`)
        : Message.success(`图片识别完毕`)
    }
  }
  // 驾驶证副页
  const backChange = (e) => {
    if (e) {
      let backArr = ['appprovedPassengerCapacity', 'grossMass', 'unladenMass', 'length', 'width', 'height']
      let newObj = Object.assign({}, e, {
        length: e.overallDimension?.length,
        width: e.overallDimension?.width,
        height: e.overallDimension?.height,
      })
      form.value.ac = form.value.ac || e.appprovedPassengerCapacity
      form.value.length = form.value.length || e.overallDimension?.length
      form.value.width = form.value.width || e.overallDimension?.width
      form.value.height = form.value.height || e.overallDimension?.height
      const grossMass = e.grossMass && e.grossMass.slice(0, -2)
      form.value.grossMass = form.value.grossMass || (grossMass ? +grossMass : '')
      const unladenMass = e.unladenMass && e.unladenMass.slice(0, -2)
      form.value.unladenMass = form.value.unladenMass || (unladenMass ? +unladenMass : '')
      backArr.some((item) => [undefined, null, ''].includes(newObj[item]))
        ? Message.warning(`未全部识别，副页图片可能不够清晰`)
        : Message.success(`图片识别完毕`)
    }
  }

  // 当用户开启etc或者tbox时，修改车牌号或者颜色提示用户
  const editCarInfoFn = () => {
    if (status.value == 'edit') {
      let { licenseNo, licenseNoColor } = originDetail.value
      let { etcEquipmentActivation = -1, tboxEquipmentStatus = -1 } = form.value
      /**
       * 1.当前用户是否开启了etc或者tbox（开启才会进入判断）
       * 2.更改的车牌号与原车牌不一样
       * 3.etc或者tbox属性是否存在form表单中（不存在既代表已经抹除了etc或tbox）
       */
      if (
        (etcEquipmentActivation == 1 || tboxEquipmentStatus != -1) &&
        (licenseNo != form.value.licenseNo || licenseNoColor != form.value.licenseNoColor) &&
        isOpenEtcOrTbox.value
      ) {
        let tboxDataArr = Object.keys(form.value).filter((item) => item.indexOf('tbox') > -1)
        let etcDataArr = Object.keys(form.value).filter((item) => item.indexOf('etc') > -1)
        let modalContent = ref(null),
          modalStatus = ref(null)
        if (
          etcEquipmentActivation == 1 &&
          (userStore.enterpriseDetail.hrhcEtcEnabled == 1 || userStore.enterpriseDetail.quantumEtcEnabled == 1)
        ) {
          // 只激活了etc
          modalContent.value = `原车牌${licenseNo}下有ETC，改车牌需重新激活etc，仍然坚持修改吗？`
          modalStatus.value = 'etc'
        } else if (tboxEquipmentStatus != -1 && userStore.enterpriseDetail.tboxEnabled == 1) {
          // 只关联了tbox
          modalContent.value = `原车牌${licenseNo}下有tbox ，改车牌需重新安装tbox，仍然坚持修改吗？`
          modalStatus.value = 'tbox'
        } else {
          // 既开启了etc也开启了tbox
          modalContent.value = `原车牌${licenseNo}下有etc和tbox，改车牌需重新激活或安装设备，仍然坚持修改吗？`
          modalStatus.value = 'etc&tbox'
        }
        if (modalContent.value) {
          Modal.info({
            hideTitle: true,
            hideCancel: false,
            content: modalContent.value,
            onOk: () => {
              // 清除etc和tbox信息
              modalStatus.value == 'etc' && etcDataArr.map((item) => delete form.value[item])
              modalStatus.value == 'tbox' && tboxDataArr.map((item) => delete form.value[item])
              modalStatus.value == 'etc&tbox' &&
                (tboxDataArr.map((item) => delete form.value[item]), etcDataArr.map((item) => delete form.value[item]))
            },
            onCancel: () => {
              form.value.licenseNoColor = licenseNoColor
              form.value.licenseNo = licenseNo
            },
          })
        }
      }
    }
  }
  let flagVin = ref(true)
  const editCarVinFn = () => {
    if (status.value == 'edit') {
      let { vin, licenseNo, etcEquipmentActivation } = originDetail.value
      let modalContent = ref(null)
      if (etcEquipmentActivation == 1 && userStore.enterpriseDetail.quantumEtcEnabled == 1 && vin != form.value.vin && flagVin.value) {
        // vin
        modalContent.value = `原车牌${licenseNo}下有ETC，改车架号需重新激活etc，仍然坚持修改吗？`
        Modal.info({
          hideTitle: true,
          hideCancel: false,
          content: modalContent.value,
          onOk: () => {
            // 清除信息
            flagVin.value = false
          },
          onCancel: () => {
            form.value.vin = vin
          },
        })
      }
    }
  }

  // 返回当前用户是否开启etc或者tbox
  const isOpenEtcOrTbox = computed(() => {
    const { hrhcEtcEnabled = null, tboxEnabled = null, quantumEtcEnabled = null } = userStore.enterpriseDetail
    return hrhcEtcEnabled == 1 || tboxEnabled == 1 || quantumEtcEnabled == 1
  })

  const carModelPopupRef = ref()
  // 选择车型
  const carModelChangeFn = (modelId, option = {}) => {
    form.value.tenantModelId = option.tenantModelId
    carModelPopupRef.value.closePopup()
  }
  const changeVehicleIdFn = () => {
    // 检测是否有重复
    let vehicleIdList = form.value.vehicleIdList
    // 清除所有的校验状态
    vehicleIdList.forEach((item, index) => {
      formRef.value.clearValidate([`vehicleIdList.${index}`])
    })
    if (vehicleIdList.length > 1) {
      let repeatList = []
      for (let i = 0; i < vehicleIdList.length; i++) {
        let item = vehicleIdList[i]
        let itemId = item.id
        if (!repeatList.includes(itemId)) {
          // 当前与后面的做比较
          for (var j = i + 1; j < vehicleIdList.length; j++) {
            let nextItem = vehicleIdList[j]
            if (itemId && itemId == nextItem.id) {
              repeatList.push(i)
              repeatList.push(j)
            }
          }
        }
      }
      // 重复数据增加提示
      if (repeatList.length > 0) {
        repeatList.forEach((repeatIndex) => {
          formRef.value.setFields({
            [`vehicleIdList.${repeatIndex}`]: {
              status: 'error',
              message: 'GPS设备重复，请处理',
            },
          })
        })
      }
    }
  }
  const rules = {
    modelId: { required: true, message: '请选择车型' },
    siteId: { required: true, message: '请选择门店' },
    licenseNo: { required: true, message: '请输入车牌号' },
    vin: { required: true, message: '请输入车架号' },
  }
  const carManageDict = usePageDict('carManageDict')
  provide('dict', carManageDict)
  provide('form', form)
  provide('status', status)
  // 车牌颜色
  const carSyncHrhcDict = usePageDict('carSyncHrhcDict')

  // 添加车型
  const newCarModelRef = ref()
  // 打开弹窗
  const addCarModelFn = () => {
    newCarModelRef.value.open()
  }
  // 更换门店
  const changeSiteFn = (val, option = {}) => {
    const { siteCarPark } = option
    form.value.libraryName = siteCarPark
  }
  // 添加车型成功
  const newCarModelSuccessFn = (id) => {
    if (id) {
      form.value.tenantModelId = id
      getCarModelDetail({ id: id }).then((res) => {
        const result = res.result
        form.value.modelId = result.modelId
        defaultModelId.value = result.modelId
      })
    }
  }
  // 车机设备
  // 新增
  const newVehicleFn = () => {
    form.value.vehicleIdList.push({})
  }
  // 删除
  const delVehicleFn = (index, isClear) => {
    if (isClear) {
      // 如果是清空，则将第一个车机信息清空
      form.value.vehicleIdList[index] = {}
    } else {
      form.value.vehicleIdList.splice(index, 1)
    }
    changeVehicleIdFn()
  }
  const upper = ref(0)
  // 解绑
  const unbindFn = () => {
    // 更新所有的车机下拉搜索
    upper.value = upper.value + 1
  }
  const formRef = ref()
  provide('sourRef', formRef)
  const okLoading = ref(false)

  /** 新增/编辑车辆信息 */
  const addEditCarInfo = (param, noticeSuccess) => {
    modifyCar(param)
      .then(() => {
        noticeSuccess()
        navigateBack()
      })
      .finally(() => {
        okLoading.value = false
      })
  }

  const submitFn = (noticeSuccess) => {
    formRef.value.validate(async (error) => {
      if (!error) {
        const param = {
          ...form.value,
        }
        // param.inspectionFileId = param.inspectionFileId?.join(',')
        // 处理车机设备字段
        let vehicleIdList = param.vehicleIdList
        if (vehicleIdList.length > 0) {
          let tempVehicleIdList = JSON.parse(JSON.stringify(vehicleIdList))
          for (var i = 0; i < tempVehicleIdList.length; i++) {
            var item = tempVehicleIdList[i]
            if (Object.keys(item).length == 0 || item.id == '') {
              tempVehicleIdList.splice(i, 1)
              i--
            }
          }
          if (tempVehicleIdList.length == 0) {
            delete param.vehicleIdList
          } else {
            param.vehicleIdList = tempVehicleIdList.map((item) => item.id)
          }
        }
        if (status.value == 'new') {
          // 处理保险 start
          let compulsory = param.compulsory
          // 商业险处理投保信息 （底部金额表格信息）
          let business = JSON.parse(JSON.stringify(param.business))
          business.forEach((item) => {
            let carInsureDetail = item.carInsureDetail
            if (carInsureDetail.length > 0) {
              for (var i = 0; i < carInsureDetail.length; i++) {
                var item2 = carInsureDetail[i]
                if (Object.keys(item2).length == 0) {
                  carInsureDetail.splice(i, 1)
                  i--
                }
              }
            }
          })
          param.carInsuranceList = [...compulsory, ...business]
        }

        delete param.compulsory
        delete param.business
        param.contractCarPurchaseEditVo.lnstalmentNum =
          param.contractCarPurchaseEditVo.useInstallment == 0 ? 1 : param.contractCarPurchaseEditVo.lnstalmentNum
        // 处理保险 end

        okLoading.value = true

        if (form.value.source == 2 && originDetail.value.licenseNo != form.value.licenseNo) {
          try {
            const _ = await checkLicenseNo({ licenseNo: param.licenseNo, vin: param.vin, carInfoId: param.id })

            const { code, result } = await checkReturnCar({ licenseNo: param.licenseNo, modelId: param.modelId })
            console.log('checkReturnCar', code, result)
            if (code == 200) {
              if (!result) {
                addEditCarInfo(param, noticeSuccess)
              } else {
                Modal.confirm({
                  title: '提示',
                  content: '当前车牌号在已归还的车辆中已存在，请确认是否需要再次借入？',
                  cancelText: '关闭',
                  okText: '再次借入',
                  onOk: () => {
                    navigateTo(
                      `/car-transfer/create?form=car-manage&source=${form.value.source}&licenseNo=${form.value.licenseNo}&modelId=${form.value.modelId}`,
                      `${form.value.licenseNo}-再次借入`
                    )
                    okLoading.value = false
                  },
                  onCancel: () => {
                    okLoading.value = false
                  },
                })
              }
            } else {
              okLoading.value = false
            }
          } catch (error) {
            console.log('error', error)
            okLoading.value = false
          }
        } else {
          addEditCarInfo(param, noticeSuccess)
        }
      }
    })
  }
</script>

<style lang="less" scoped>
  .car-manage-alert {
    align-items: flex-start;
  }
  .mr-20px {
    margin-right: 20px;
  }
  .operate-list {
    position: absolute;
    right: -236px;
    margin-left: -40px;

    .operate-btn {
      margin-right: 16px;
    }
  }
  .upload-button {
    padding: 5px 18px;
    background: #1890ff;
    border-radius: 2px;
    font-weight: 400;
    font-size: 14px;
    color: #ffffff;
  }
  .upload-wrapper {
    padding: 20px 0 0;
  }
  .page-form-block {
    width: 100%;
    background: rgba(247, 248, 250, 0.5);
    padding: 20px 20px 0 20px;
  }

  .empty-custom-fee {
    justify-content: center;
    :deep(.arco-empty) {
      .arco-empty-description {
        color: #d8d8d8;
        font-size: 12px;
      }
      .arco-icon {
        color: #d8d8d8;
      }
    }
  }
</style>
